<template>
  <div class="dashboard-container">
    <div class="app-container">
      <Hint>
        <!-- 根据type是否为1 和 2(后端判断) 判断添加的是一级权限还是children二级权限  0 为顶级权限 同级下 -->
        <el-button slot="after" type="primary" size="small" @click="addPower(1, '0')">添加权限</el-button>
      </Hint>
      <el-table border style="margin-top: 10px" :data="list" row-key="id">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="标识" align="center" prop="code" />
        <el-table-column label="描述" align="center" prop="description" />
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <!-- 二级树形菜单不显示添加按钮 -->
            <el-button
              v-show="row.type !== 2"
              type="text"
              style="color: #67c23a"
              @click="addPower(2, row.id)"
            >添加</el-button>
            <!-- 根据2 判断添加的是子节点 根据id判断添加的为谁的子节点 -->
            <el-button type="text" @click="redactPower(row.id)">编辑</el-button>
            <el-button
              type="text"
              style="color: #f56c6c"
              @click="delFn(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 动态弹窗 -->
    <component :is="AddPermissions" ref="addPer" :show-progress.sync="showProgress" />
  </div>
</template>

<script>
import { getPermissionListApi, delUserPerApi, getUserAssignApi } from '@/api'
import { getDepartments } from '@/utils'
import AddPermissions from './components/add-permissions.vue'
export default {
  components: {
    AddPermissions
  },
  data() {
    return {
      AddPermissions: 'AddPermissions', // 动态组件
      list: [], // 权限列表
      showProgress: false // 弹出框状态
    }
  },
  created() {
    this.getPermissionList()
  },

  methods: {
    // 获取所有权限列表
    async getPermissionList() {
      this.list = getDepartments(await getPermissionListApi(), '0')
      console.log(this.list)
    },

    // 点击 -> 删除
    async delFn(id) {
      try {
        await this.$confirm('确认删除此权限点吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await delUserPerApi(id)
        this.getPermissionList()
        this.$message.success('删除此权限成功')
      } catch (error) {
        this.$notify({
          title: '提示',
          message: '已取消操作'
        })
      }
    },

    // 添加权限
    addPower(type, pid) {
      // 将辨识 类型 和 pid传给子组件
      // 将 type标识 pid添加给子节点 表单数据中
      this.$refs.addPer.formData = { ...this.$refs.addPer.formData, type, pid }
      this.showProgress = true
    },

    // 点击 -> 编辑
    async redactPower(id) {
      this.$refs.addPer.formData = await getUserAssignApi(id)
      this.showProgress = true
    }
  }
}
</script>

<style lang="scss" scoped></style>
